import Game from "../common/game/Game"
import SnakeMod from "./model/SnakeMod"
import PlayerSnake from "../common/game/snake/PlayerSnake"
import EventDispatcher from "../common/core/EventDispatcher"
import { ClientEvent } from "./event/ClinetEvent"
import FoodMod from "./model/FoodMod"
import WorldMod from "./model/WorldMod"
import ProtoDispatcher from "../common/core/ProtoDispatcher"
import { ISize } from "../common/game/util/V2Util"
import BaseMod from "./core/mvc/BaseMod"
import Conn from "./network/Conn"
import { Protocol } from "../common/protocol/Protocol"

/** 应用全局 */
export default class App {

    private static _localGame: Game
    private static _ed = new EventDispatcher<ClientEvent.Def>()
    private static _pd: ProtoDispatcher
    private static _isLocal = false
    private static _playerId: number
    private static _localPlayer: PlayerSnake
    private static _isReady = false
    private static _conn: Conn

    static get isReady() { return App.isReady }
    static get isLocal() { return App._isLocal }
    static get localPlayer() { return App._localPlayer }
    static get localGame() { return App._localGame }
    static get playerId() { return App._playerId }
    static get ed() { return App._ed }
    static get pd() { return App._pd }
    static get conn() { return App._conn }

    private static _models: BaseMod[] = []

    static startLocal(playerName: string) {
        App._isLocal = true
        let game = App._localGame = new Game()
        game.start()
        App._localPlayer = game.join(playerName)
        App._playerId = App._localPlayer.id
        App.initModel()
    }

    static startRemote(playerId: number, conn: Conn) {
        App._conn = conn
        App._pd = conn.pd
        App._isLocal = false
        App._playerId = playerId
        App.initModel()
    }

    static initModel() {
        App._models.push(
            WorldMod.ins,
            SnakeMod.ins,
            FoodMod.ins
        )
    }

    static ready() {
        if (!App._isReady) {
            App._isReady = true
            App._models.forEach(model => {
                model.ready()
            })
            if (!App._isLocal) {
                App._conn.send(Protocol.C2S_READY)
            }
        }
    }
}